package com.atstudying.mall.product.service.impl;

import com.atstudying.common.utils.PageUtils;
import com.atstudying.common.utils.Query;
import com.atstudying.mall.product.dao.SkuInfoDao;
import com.atstudying.mall.product.entity.SkuImagesEntity;
import com.atstudying.mall.product.entity.SkuInfoEntity;
import com.atstudying.mall.product.entity.SpuInfoDescEntity;
import com.atstudying.mall.product.service.AttrGroupService;
import com.atstudying.mall.product.service.SkuInfoService;
import com.atstudying.mall.product.service.SkuSaleAttrValueService;
import com.atstudying.mall.product.service.SpuInfoDescService;
import com.atstudying.mall.product.vo.SkuItemSaleAttrsVo;
import com.atstudying.mall.product.vo.SkuItemVo;
import com.atstudying.mall.product.vo.SpuItemAttrGroupVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesServiceImpl imagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;


    @Autowired
    ThreadPoolExecutor executors;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {

        this.baseMapper.insert(skuInfoEntity);
    }

    /**
     * sku检索
     * @param params
     * @return
     * {
    page: 1,//当前页码
    limit: 10,//每页记录数
    sidx: 'id',//排序字段
    order: 'asc/desc',//排序方式
    key: '华为',//检索关键字
    catelogId: 0,
    brandId: 0,
    min: 0,
    max: 0
    }
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){


            queryWrapper.and(w->{
                w.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        //上面的 queryWrapper.and代表如下意思
        //status=1 and (id=1 or spu_name like xxx)
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);

        }


        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)){
            queryWrapper.eq("brand_id",brandId);

        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)){

            queryWrapper.ge("price",min);
        }
        String max = (String) params.get("max");


        if (!StringUtils.isEmpty(max)){
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if (                bigDecimal.compareTo(new BigDecimal("0"))==1){
                    queryWrapper.le("price",max);

                }

            }catch (Exception e){

            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {

        List<SkuInfoEntity> list = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return list;
    }


    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {

        SkuItemVo skuItemVo=new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1：sku基本信息获取 pms_sku_info
            SkuInfoEntity skuInfoEntity = getById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            System.out.println(skuInfoEntity+"...skuInfoEntity");
            return skuInfoEntity;
        },executors );

        CompletableFuture<Void> imagesFuture = CompletableFuture.runAsync(() -> {
            //2：sku图片信息 pms_sku_images
            List<SkuImagesEntity> images = imagesService.getImageBySkuId(skuId);
            skuItemVo.setImages(images);

        }, executors);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3：获取spu的销售属性组合
            /**
             * 传入了spuId
             * 1.分析当前spu有多少个sku，所有涉及得到的属性组合
             * 2：要把相同属性的值，收集起来
             */
            List<SkuItemSaleAttrsVo> saleAttr = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttr);
            System.out.println(saleAttr + "...........");
        }, executors);
        //这两个id可以让我们知道很多东西
//        Long spuId = skuInfoEntity.getSpuId();
//        Long catalogId = skuInfoEntity.getCatalogId();

        CompletableFuture<Void> spuInfoDescFuture = infoFuture.thenAcceptAsync((res) -> {
            //4：获取spu的介绍
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesp(spuInfoDescEntity);
        }, executors);

        CompletableFuture<Void> groupAttrsFuture = infoFuture.thenAcceptAsync((res) -> {
            //5：获取spu的规格参数信息
            /**
             * 思路：1：得知道当前spu有多少属性分组   private String groupName; attrName attrValues
             */
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(groupAttrs);
            System.out.println(groupAttrs+"...groupAttrs");

//        System.out.println(groupAttrs);
        }, executors);

        //get方法一定要加，它会等待所有操作完成，才可以执行异步结束操作
        CompletableFuture.allOf(infoFuture,imagesFuture,saleAttrFuture,spuInfoDescFuture,groupAttrsFuture).get();
        System.out.println("异步操作完成。。。。");

        return skuItemVo;
    }

}